<script setup lang="ts">
import { ref, reactive, toRef, PropType, watch, nextTick } from "vue";
import type { FormRules, UploadProps } from "element-plus";
import WangEditorBase from "@/components/wangEditorBase.vue";
import SimpleTagSelector from "@/components/SimpleTagSelector/index.vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { TagInfo } from "@/api/tag-management";

export interface ArticleFormData {
  id?: number;
  title: string;
  content: string;
  author: string;
  publish_time: string;
  description: string;
  category_id: number | null;
  status: number;
  user_id: number;
  image: string;
  tags?: TagInfo[];
}

const props = defineProps({
  formInline: {
    type: Object as PropType<ArticleFormData>,
    default: () => ({})
  },
  categoryTreeData: {
    type: Array,
    default: () => []
  }
});

const ruleFormRef = ref();
const wangEditorRef = ref();
const editorKey = ref(0); // 用于强制重新渲染 WangEditor

const newFormInline = ref<ArticleFormData>({
  id: props.formInline.id || undefined,
  title: props.formInline.title || "",
  content: props.formInline.content || "",
  author: props.formInline.author || "",
  publish_time: props.formInline.publish_time || "",
  category_id: props.formInline.category_id || null,
  status: props.formInline.status || 0,
  user_id: props.formInline.user_id || 1,
  image: props.formInline.image || "",
  description: props.formInline.description || "",
  tags: Array.isArray(props.formInline.tags) ? props.formInline.tags : []
});

const categoryTree = toRef(props, "categoryTreeData");

// 监听 props.formInline 的变化，更新 newFormInline
watch(
  () => props.formInline,
  (newVal, oldVal) => {
    const isReset = !newVal.id && !newVal.title && !newVal.content;

    Object.assign(newFormInline.value, newVal);
    newFormInline.value.image = newVal.image || "";
    newFormInline.value.tags = Array.isArray(newVal.tags) ? newVal.tags : [];

    if (isReset && ruleFormRef.value) {
      nextTick(() => {
        ruleFormRef.value?.clearValidate();
      });
    }
  },
  { deep: true, immediate: true }
);

const formRules = reactive<FormRules>({
  title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
  // content: [{ required: true, message: "请输入文章内容", trigger: "blur" }],
  author: [{ required: true, message: "请输入作者", trigger: "blur" }],
  category_id: [{ required: true, message: "请选择文章分类", trigger: "change" }]
});

const handleImageSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  if (response.code === 200) {
    newFormInline.value.image = import.meta.env.VITE_BASE_URL + response.data.url;
    ElMessage.success("图片上传成功");
  } else {
    ElMessage.error("图片上传失败");
  }
};

const handleImageRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  newFormInline.value.image = "";
  ElMessage.info("图片已移除");
};

const beforeImageUpload: UploadProps["beforeUpload"] = rawFile => {
  const isJPG = rawFile.type === "image/jpeg" || rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("图片只能是 JPG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

// 处理标签变化
const handleTagsChange = (tags: TagInfo[]) => {
  console.log("标签变化:", tags); // 调试日志
  newFormInline.value.tags = tags;
};

const emits = defineEmits(["submit"]);

function getRef() {
  return ruleFormRef.value;
}

const submitForm = async () => {
  const formEl = ruleFormRef.value;
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      emits("submit", newFormInline.value);
    }
  });
};

const resetForm = () => {
  Object.assign(newFormInline.value, {
    id: undefined,
    title: "",
    content: "",
    author: "",
    publish_time: "",
    category_id: null,
    status: 0,
    user_id: 1,
    image: "",
    description: "",
    tags: []
  });

  // 强制重新渲染 WangEditor 组件
  editorKey.value++;

  if (ruleFormRef.value) {
    ruleFormRef.value.clearValidate();
  }
};

defineExpose({ getRef, submitForm, resetForm });
</script>

<template>
  <el-form ref="ruleFormRef" :model="newFormInline" :rules="formRules" label-width="80px">
    <el-form-item label="文章标题" prop="title">
      <el-input v-model="newFormInline.title" clearable placeholder="请输入文章标题" />
    </el-form-item>
    <el-form-item label="作者" prop="author">
      <el-input v-model="newFormInline.author" clearable placeholder="请输入作者" />
    </el-form-item>
    <el-form-item label="分类" prop="category_id">
      <el-tree-select
        v-model="newFormInline.category_id"
        :data="categoryTree"
        :props="{ label: 'name', value: 'id' }"
        check-strictly
        node-key="id"
        clearable
        placeholder="请选择文章分类"
        class="w-full"
      />
    </el-form-item>
    <el-form-item label="文章封面" prop="image">
      <el-upload
        class="avatar-uploader"
        action="/api/upload-file"
        :show-file-list="false"
        :on-success="handleImageSuccess"
        :before-upload="beforeImageUpload"
        :on-remove="handleImageRemove"
      >
        <img v-if="newFormInline.image" :src="newFormInline.image" class="avatar" />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-input v-model="newFormInline.image" placeholder="或输入文章封面链接（可选）" style="width: 500px" />
    </el-form-item>
    <el-form-item label="文章简介" prop="description">
      <el-input v-model="newFormInline.description" type="textarea" placeholder="请输入文章简介" :rows="3" />
    </el-form-item>
    <el-form-item label="文章标签" prop="tags">
      <SimpleTagSelector v-model="newFormInline.tags" :max-tags="10" @change="handleTagsChange" />
    </el-form-item>
    <el-form-item label="内容" prop="content">
      <WangEditorBase
        v-if="editorKey > 0"
        :key="editorKey"
        ref="wangEditorRef"
        v-model="newFormInline.content"
      />
    </el-form-item>
  </el-form>
</template>

<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 250px;
  height: 178px;
}

.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
  border: 1px solid #d9d9d9;
}
</style>
